"""
Created on 2018/4/26 16:41 星期四
@author: Matt  zhuhan1401@126.com
Description: svm 实现乳腺癌检测
"""

from sklearn.svm import SVC
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split,ShuffleSplit,GridSearchCV
from commonTool.plotCurve import plot_learning_curve,plot_param_curve
import numpy as np
from matplotlib import pyplot as plt


def SVCWithRBF(X, Y):
    # 自动选择参数
    gammas = np.linspace(0, 0.0003, 30)
    paramGrid = {'gamma': gammas}
    clf = GridSearchCV(SVC(), paramGrid, cv=5)
    clf.fit(X, Y)
    plt.figure(figsize=(10, 4), dpi=144)
    plot_param_curve(gammas, clf.cv_results_, xlabel='gamma')
    plt.show()

def SVCWithPoly(X,Y):
    if __name__ == '__main__':
        cv = ShuffleSplit(n_splits=10, test_size=0.2, random_state=0)
        title='Learning Curve with degree={0}'
        degrees=[1,2]
        plt.figure(figsize=(12,4),dpi=144)
        for i in range(len(degrees)):
            plt.subplot(1,len(degrees),i+1)
            plot_learning_curve(SVC(C=1.0,kernel='poly',degree=degrees[i]),
                                title.format(degrees[i]),X,Y,cv=cv,ylim=(0.8,1.01),n_jobs=4)
        # plt.show()


cancer=load_breast_cancer()
X=cancer.data
Y=cancer.target
XTrain,XTest,YTrain,YTest=train_test_split(X,Y,test_size=0.2)

# clf=SVC(C=1.0,kernel='rbf',gamma=0.0001)
# # gamma使用0.1 和 0.0001 差距非常大 gamma=0.1时为过拟合
# clf.fit(XTrain,YTrain)
# cv=ShuffleSplit(n_splits=10,test_size=0.2,random_state=0)
# plot_learning_curve(clf, "Learn Curve for SVM(rbf)", X, Y, ylim=(0.0, 1.01), cv=cv)
# plt.show()

# SVCWithRBF(X, Y) #自动选择最佳的gamma参数
# 使用一阶、二阶多项式核函数进行训练
SVCWithPoly(X,Y)

